import {getToken, setToken, removeToken,setRefreshToken,removeRefreshToken} from '@/utils/auth'
import {login, getUserInfo, logout} from '@/api/system/user'
import router from "@/router";
import store from "@/store";
import Layout from "@/views/layout/Layout";

const user = {
    state: {
        token: getToken(),
        id: '',
        name: '',
        nickname: '',
        avatar: '',
        type: '',
        roleId: [],
        menu: [],
        routerMenu: [],
        permission: []
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ID: (state, id) => {
            state.id = id
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_TYPE: (state, type) => {
            state.type = type
        },
        SET_NICKNAME: (state, nickname) => {
            state.nickname = nickname
        },
        SET_ROLE_ID(state, roleId) {
            state.roleId = roleId
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_MENU: (state, menu) => {
            state.menu = menu
        },
        SET_ROUTER_MENU(state, menu) {
            state.routerMenu = menu
        },
        SET_PERMISSION(state, permission) {
            state.permission = permission
        }
    },

    actions: {
        //登录
        goLogin(context, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    const {access_token, token_type,refresh_token} = res.data
                    const token = token_type + " " + access_token
                    context.commit('SET_TOKEN', token)
                    setToken(token)
                    setRefreshToken(refresh_token)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        //获取用户信息
        getUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    if (res.status) {
                        //用户信息,左侧导航菜单,按钮权限
                        const {userInfo,menuList,permissionList} = res.data
                        // commit('SET_NAME', userInfo.username)
                        commit('SET_ID', userInfo.id)
                        commit('SET_NICKNAME', userInfo.nickname)
                        // commit('SET_TYPE', userInfo.userType)
                        // commit('SET_AVATAR', userInfo.avatar)
                        commit('SET_ROLE_ID', userInfo.roleIds)

                        commit('SET_MENU', menuList)
                        commit('SET_PERMISSION', permissionList)
                        //生成动态路由（主要是获取子路由，生成component）
                        addDynamicMenuRoutes(menuList)
                        resolve(res)
                    } else {
                        reject(res.msg)
                    }
                }).catch(err => {
                    reject(err)
                })
            })
        },

        //刷新token
        refreshToken({commit}, refreshToken) {
            commit('SET_TOKEN', undefined)
            return new Promise((resolve, reject) => {
                login({
                    grant_type: 'refresh_token',
                    refresh_token: refreshToken,
                }).then(res => {
                    if (res.status) {
                        const {access_token, token_type} = res.data;
                        const token = token_type + " " + access_token;
                        commit('SET_TOKEN', token);
                        setToken(token);
                        resolve(token);
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //注销
        logout({commit}) {
            return new Promise(resolve => {
                logout().then(res => {
                    if (res.status) {
                        commit('SET_TOKEN', '');
                        commit('SET_MENU', '');
                        sessionStorage.clear();
                        removeToken();
                        removeRefreshToken();
                        this.$message.success("注销成功");
                        resolve();
                    }
                })
                router.replace("/login");
            })
        },
    }
}


/**
 * 生成动态路由（主要是获取子路由，生成component）
 * @param menuList 菜单列表
 */
function addDynamicMenuRoutes(menuList) {
    let children = fnAddDynamicMenuRoutes(menuList);
    let temp = []
    temp.push({
        path: '/',
        component: Layout,
        children: children
    })
    temp.push({path: '*', redirect: {name: '404'}})
    router.addRoutes(temp)
}


/**
 * 获取路由
 * @param {*} menuList 菜单列表
 * @param {*} routesArr 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routesArr = []) {
    let dataArr = []
    for (let i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
            dataArr = dataArr.concat(menuList[i].children)
        } else if (menuList[i].url) {
            let route = {
                path: menuList[i].url,
                component: () => import (`@/views${menuList[i].url}`),
                meta: {
                    menuId: menuList[i].menuId,
                    title: menuList[i].name,
                }
            }
            routesArr.push(route)
        }
    }
    if (dataArr.length >= 1) {
        fnAddDynamicMenuRoutes(dataArr, routesArr)
    }
    return routesArr;
}

export default user
